package com.engine.ch.action;

import com.alibaba.fastjson.JSON;
import com.api.doc.detail.service.DocSaveService;
import com.api.doc.detail.util.SendMsgForNewDocThread;
import com.api.workflow.util.ServiceUtil;
import com.engine.workflow.biz.requestForm.SaveDocDetailBiz;
import com.engine.workflow.biz.requestForm.WfToDocBiz;
import com.engine.workflow.biz.requestForm.WfWaterMark4WfToDocBiz;
import com.engine.workflow.entity.WorkflowToDocSettingInfoEntity;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.alioss.AliOSSObjectManager;
import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.DocManager;
import weaver.docs.docs.ImageFileIdUpdate;
import weaver.docs.docs.VersionIdUpdate;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.FWHttpConnectionManager;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.interfaces.workflow.action.RequestDocPropManager;
import weaver.interfaces.workflow.action.WorkflowToDoc;
import weaver.soa.workflow.request.RequestInfo;
import weaver.system.SystemComInfo;
import weaver.weaversso.CreateTokenUtil;
import weaver.workflow.mode.FieldInfo;
import weaver.workflow.msg.PoppupRemindInfoUtil;
import weaver.workflow.request.RequestManager;
import weaver.workflow.workflow.WorkflowConfigComInfo;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WorkflowToPdfAction implements Action {


    private static final Logger log = LoggerFactory.getLogger(WorkflowToDoc.class);

    private final static int THREAD_NUM = 10;//10个固定线程池
    private final static ExecutorService expPool = Executors.newFixedThreadPool(THREAD_NUM);//使用线程池进行线程管理

    private static ImageFileIdUpdate imageFileIdUpdate = new ImageFileIdUpdate();

    private static VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

    private static Pattern port_pattern = Pattern.compile("^\\w*[\\s\\S]+(:\\d+)", Pattern.CASE_INSENSITIVE);

    private String isaesencrypt="";
    private String aescode="";

    //底部签字意见列表显示数量
    private int pageSize =100;
    private Integer fileId;

    public Integer getFileId() {
        return fileId;
    }

    public void setFileId(Integer fileId) {
        this.fileId = fileId;
    }

    public static Class<?> class_MultiLangFilter;
    static {
        try {
            class_MultiLangFilter = Class.forName("weaver.filter.MultiLangFilter");
        } catch (ClassNotFoundException e) {
            log.info("class MultiLangFilter doesn't exist");
        }
    }

    public String execute(RequestInfo request) {
        log.info("流程转文档开始……workflowToDoc start");
        String cookie = null;
        if (class_MultiLangFilter!=null) {
            try {
                cookie = (String)class_MultiLangFilter.getMethod("getThreadlocalCookies").invoke(class_MultiLangFilter);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        RequestManager requestManager = request.getRequestManager();
        String requestid = Util.null2String(request.getRequestid());
        String userid = Util.null2String(request.getLastoperator());
        String requestname = Util.null2String(request.getDescription());
        String workflowid = Util.null2String(request.getWorkflowid());
        Start(requestid, userid, requestname, workflowid, cookie,requestManager);
        log.info("流程转文档结束……workflowToDoc end");
        return Action.SUCCESS;
    }

    //接口存文档
    public boolean Start(String requestid, String userid, String requestname, String workflowid, String cookie,RequestManager requestManager) {
        requestManager = getRequestManager(requestManager,requestid);
        return Start(requestid, userid, requestname, workflowid, cookie,requestManager,true);
    }

    //批量存文档用
    public boolean Start(String requestid, String userid, String requestname, String workflowid, String cookie) {
        RequestManager requestManager = null;
        requestManager = getRequestManager(requestManager,requestid);
        return Start(requestid, userid, requestname, workflowid, cookie,requestManager,false);
    }
    /**
     * start
     *
     * @param requestid
     *            流程id
     * @param userid
     *            用户id
     * @param requestname
     *            流程名 流程名作为文档的文档名
     * @param workflowid
     *            流程类型id
     */
    public boolean Start(String requestid, String userid, String requestname, String workflowid, String cookie,RequestManager requestManager,boolean isfromaction) {
        String src = requestManager.getSrc(); //用于判断是否流程监控干预
        User user = new User(Util.getIntValue(userid));
        //String wfdocpath = Util.null2String(getWfDocPath(workflowid));
        WfToDocBiz wfbiz = new WfToDocBiz();
        String wfdocpath = Util.null2String(wfbiz.getWfDocPath(workflowid,requestid));
        String docfiles = getDocFiles(workflowid);
        if ("".equals(docfiles)){
            log.error("流程保存为文档失败，因为未勾选文档附件复选框");
            return false;
        }
        //在这里先获取到modeid 线程中获取时流程可能已经到了下个节点导致模板获取的不对
        int nodeid = requestManager.getNodeid();
        com.api.workflow.util.ServiceUtil serviceUtil = new ServiceUtil();
        if (!isfromaction)
            nodeid = serviceUtil.getCurrentNode(requestid,user);
        String modeid = wfbiz.getModeid(Util.getIntValue(workflowid),Util.getIntValue(requestid),nodeid);

        int keepsign =  getKeepSign(workflowid);
        //增加配置文件 是否异步生成
        String isSync = Util.null2String(new WorkflowConfigComInfo().getValue("workflowtodoc_issync"));
            String filename = UUID.randomUUID().toString();  //防止高并发文件名重复
            String temppath = getFileSavePath();
            LinkedHashMap<String, String> fileids = new LinkedHashMap<String, String> ();
            //是否开启水印
            boolean isOpenWaterMark = WfWaterMark4WfToDocBiz.isOpenWaterMark(Util.getIntValue(workflowid));
            String onlineHtmlMethod = Util.null2String(new WorkflowConfigComInfo().getValue("onlineHtmlMethod"));

            if (docfiles.contains("1")) {  //在线html
                if (!onlineHtmlMethod.equals("1")){   //走离线的方法
                    generateOnLineHtml(requestid,userid, requestname, workflowid,wfdocpath, cookie,fileids,isOpenWaterMark);
                }
            }
            //离线html/pdf
            WfToDocBiz wfToDocBiz = new WfToDocBiz(user,pageSize,keepsign,docfiles,modeid,isOpenWaterMark);
            wfToDocBiz.setOnlineHtmlMethod(onlineHtmlMethod);
            wfToDocBiz.generatepdfandhtml(requestid,filename,temppath,src);
            fileids.putAll(wfToDocBiz.getfileids(requestname,filename,temppath));
            //保存
            saveDocDetail(requestname, workflowid,requestid, wfdocpath,userid,fileids,requestManager,wfbiz);
        return true;
    }


    private void generateOnLineHtml(String requestid, String userid, String requestname, String workflowid,String wfdocpath, String cookie,LinkedHashMap<String, String> fileids,boolean isOpenWaterMark){
        String url[] = getUrl(requestid, userid);

        if(url!=null && url.length==5){//避免url为空时，出现异常
            boolean hasNull = false;//检查5个值是不是有空，如果有，就不导为文档了
            /*
             * QC271940解决AD域用户使用流程存为文档功能
             */
			/*for(int cx=0; cx<url.length; cx++){
				if(url[cx]==null || "".equals(url[cx])){
					hasNull = true;
				}
			}*/
            if(hasNull == false){
                log.info("生成HTML……");
                getWorkflowHtml(url, requestid, requestname, workflowid, wfdocpath,userid, cookie,fileids);
            }
        }else{
            log.info("URL数据错误："+ JSON.toJSONString(url));
        }
    }

    /**
     * 获取流程的url
     *
     * @param requestid
     *            流程id
     * @param userid
     *            当前用户
     * @return
     */
    public String[] getUrl(String requestid, String userid) {
        String sql = "";
        String tempurl = "";
        String loginid = "";
        String password = "";
        int accounttype = 0;  //账号类型,0:主账号，1：次账号
        int belongto = 0;
        String isADaccount="";
        String para = "";
        String oaaddress = "";
        String params[] = new String[5];

        RecordSet rs = new RecordSet();
        sql = "select * from SystemSet";
        rs.executeSql(sql);
        rs.next();
        oaaddress = Util.null2String(rs.getString("oaaddress"));
        if (oaaddress.equals("")) {
            log.error("流程保存为文档失败，因为系统未设置OA访问地址,requestid=" + requestid);
            return params;
        }

        sql = "select * from hrmresource where id = " + userid;
        rs.executeSql(sql);
        while (rs.next()) {
            loginid = rs.getString("loginid");
            password = rs.getString("password");
            isADaccount = rs.getString("isadaccount");
            accounttype = Util.getIntValue(Util.null2String(rs.getString("accounttype")),0);
            belongto = Util.getIntValue(Util.null2String(rs.getString("belongto")));
        }

        sql = "select * from HrmResourceManager where id = " + userid;
        rs.executeSql(sql);
        while (rs.next()) {
            loginid = rs.getString("loginid");
            password = rs.getString("password");
        }

        String f_weaver_belongto_userid = "";
        String f_weaver_belongto_usertype = "0";
        if(accounttype == 1 && belongto > 0){   //次账号，查询主账号，用主账号登录
            f_weaver_belongto_userid = userid;
            sql = "select * from hrmresource where id = " + belongto;
            rs.executeSql(sql);
            if(rs.next()){
                isADaccount = rs.getString("isadaccount");
                loginid = rs.getString("loginid");
                password = rs.getString("password");
            }
        }

        if ((!loginid.equals("") && !password.equals(""))||(!loginid.equals("")&&isADaccount.equals("1"))) {//QC271940[80][90]Ldap集成-解决AD用户无法使用流程存为文档功能
            para = "/workflow/request/ViewRequest.jsp?haveVerifyForward=true&requestid=" + requestid
                    + "&para2=" + loginid + "&para3=" + password;
        } else {
            log.error("流程保存为文档失败，因为用户名和密码为空,requestid=" + requestid);
            return params;
        }

        tempurl = oaaddress
                + "/login/VerifyRtxLogin.jsp?urlfrom=workflowtodoc&para1="
                + para;

        Map<String, String> result = CreateTokenUtil.createToken("ecology", loginid);
        String token = "";
        if ("success".equals(result.get("state"))){
            token = result.get("data");             //tokenֵ
        } else {
            String msg = result.get("data");
        }

//		params[0] = oaaddress+"/login/VerifyRtxLogin.jsp";
        params[0] = oaaddress+"/wui/index.html?ssoToken="+token+"#/main";
        params[1] = "workflowtodoc";
        String pageurl = "/workflow/request/ViewRequest.jsp?haveVerifyForward=true&isworkflowhtmldoc=1&requestid=" + requestid;
        if(accounttype > 0 && belongto > 0){
            pageurl += "&f_weaver_belongto_userid=" + f_weaver_belongto_userid + "&f_weaver_belongto_usertype=" + f_weaver_belongto_usertype;
        }
        params[2] = pageurl;
		/*try {
			params[3] = new String(loginid.getBytes(), "8859_1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        params[3] = PoppupRemindInfoUtil.encrypt(loginid);//解决中文账号问题
        params[4] = password;


        return params;
    }

    /**
     * 根据url读取html文件，并生成文档，放到指定的目录下
     *
     * @param url
     *            流程页面的url
     *
     * @param requestid
     *            流程id
     * @param requestname
     *            流程名称
     * @param workflowid
     *            流程类型id
     * @param wfdocpath
     *            文档存放的目录
     */
    public void getWorkflowHtml(String url[], String requestid,
                                String requestname, String workflowid, String wfdocpath,String userid, String cookie,LinkedHashMap<String, String> fileids) {

        HttpClient client =  FWHttpConnectionManager.getHttpClient();

        PostMethod method = new PostMethod(url[0]);//oa地址
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            NameValuePair[] params = {
                    new NameValuePair("urlfrom", url[1]),//urlfrom
                    new NameValuePair("para1",url[2]),//requesturl
                    new NameValuePair("para2",url[3] ),//loginid
                    new NameValuePair("para3",url[4])};//url4密码
            method.setRequestBody(params);
            //log.info("----workflowtodoc----"+url[0] + "?urlfrom="+url[1]+"&para1="+url[2]+"&para2="+url[3]+"&para3="+url[4]);


            int statusCode = client.executeMethod(method);
            new BaseBean().writeLog("WorkflowToDoc statusCode :"+statusCode);
            String temppath = getFileSavePath();
            String filename = System.currentTimeMillis() + "";
            String htmlname = temppath + filename;
            File _temppath = new File(temppath);
            if(!_temppath.exists()){
                _temppath.mkdirs();
            }

            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_OK) {
                Header locationHeader = method.getResponseHeader("location");
                if (locationHeader != null) {
                    String tempurl = locationHeader.getValue();
                    if(!tempurl.startsWith("http://") && !tempurl.startsWith("https://")) {
                        //GET PORT
                        String port_string = "";
                        Matcher matcher = port_pattern.matcher(url[0]);
                        if (matcher.find()) {
                            port_string = matcher.group(1);
                        }
                        tempurl = "http://"
//								+ (port_string.isEmpty()? "" : "localhost"+port_string)
                                + (port_string.isEmpty()? "" : "127.0.0.1"+port_string)
                                + tempurl;

                    }
                    new BaseBean().writeLog("WorkflowToDoc cookie :"+cookie);
                    tempurl = getFinallyUrl(client, tempurl,cookie);
                    tempurl = tempurl.replaceFirst(".jsp", "Iframe.jsp");
                    tempurl = tempurl+"&urlfrom=workflowtodoc";

                    new BaseBean().writeLog("WorkflowToDoc client.executeMethod(g) start :"+System.currentTimeMillis());
                    new BaseBean().writeLog("WorkflowToDoc tempurl :"+tempurl);
                    GetMethod g = new GetMethod(tempurl);
                    g.setRequestHeader("cookie", cookie);
                    client.executeMethod(g);
                    OutputStream os=new FileOutputStream(htmlname);

                    new BaseBean().writeLog("WorkflowToDoc client.executeMethod(g) end :"+System.currentTimeMillis());
//					SystemComInfo syscominfo=new SystemComInfo() ;
//					this.isaesencrypt = syscominfo.getIsaesencrypt();
//					this.aescode = Util.getRandomString(13);
//					if("1".equals(this.isaesencrypt)){
//						try{
//							os=AESCoder.encrypt(os, this.aescode);
//						} catch(Exception e){
//
//						}
//					}
                    OutputStreamWriter output = new OutputStreamWriter(os, "UTF-8");
                    BufferedWriter bw = new BufferedWriter(output);

                    BufferedReader in = new BufferedReader(new InputStreamReader(g.getResponseBodyAsStream(), "UTF-8"));
                    StringBuffer sb=new StringBuffer();
                    String line = in.readLine();
                    while (line != null) {
                        line = line.trim();
                        if(line.indexOf("</a>")>=0&&line.indexOf("openSignPrint()")>=0&&line.indexOf("onclick")>=0){
                            //去掉转发按钮
                        }else if(line.indexOf("<img")>=0&&line.indexOf("class=\"transto\"")>=0&&line.indexOf("onclick")>=0&&line.indexOf("transtoClick(this)")>=0){

                        }else if(line.indexOf("var")>=0&&line.indexOf("bar")>=0&&line.indexOf("eval")>=0&&line.indexOf("handler")>=0&&line.indexOf("text")>=0){
                            sb.append("var bar=eval(\"[]\");\n");
                        }else{
                            sb.append(line + "\n");
                        }
                        line = in.readLine();
                    }

                    //添加水印
                    if(WfWaterMark4WfToDocBiz.isOpenWaterMark(Util.getIntValue(workflowid))){
                        WfWaterMark4WfToDocBiz wfWaterMark4WfToDocBiz = new WfWaterMark4WfToDocBiz(new User(Util.getIntValue(userid)));
                        wfWaterMark4WfToDocBiz.generateFormData(requestid);
                        String watetmarkhtml = wfWaterMark4WfToDocBiz.getWaterMarkHtml(false,Util.getIntValue(workflowid),Util.getIntValue(requestid),true);
                        int begIndex = sb.lastIndexOf("</body>");
                        String frontcontent = sb.substring(0, begIndex);
                        String behindcontent = sb.substring(begIndex);
                        sb.setLength(0);
                        sb.append(frontcontent)
                                .append("\n").append(watetmarkhtml)
                                .append(behindcontent);
                    }

                    //去掉ext的button,<script type="text/javascript" src="/js/wf_wev8.js">var bar=eval("[]");</script>
                    sb.append("<script type=\"text/javascript\">\n");
                    sb.append("function drm4request2doc(){\n");
                    sb.append("\tbar=eval(\"[]\");\n");
                    sb.append("\tdocument.getElementById(\"rightMenu\").style.display=\"none\";\n");
                    sb.append("}\n");
                    sb.append("window.attachEvent(\"onload\", drm4request2doc);\n");
                    sb.append("</script>");

                    String sdata=sb.toString();
                    bw.write(sdata,0,sdata.length());

//					long size = 0l;
//					File f = new File(htmlname);
//					if (f.exists()) {
//						size = f.length();
//					}

                    bw.flush();
                    bw.close();
                    in.close();

                    InputStream inputStream = null;
                    byte[] buffer = null;
                    File file = new File(htmlname);
                    if (file.exists()){
                        try {
                            inputStream = new FileInputStream(file);
                            buffer = new byte[(int) file.length()];
                            inputStream.read(buffer);
                            inputStream.close();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

//
//					if("1".equals(this.isaesencrypt)){
//						String sm4 = Util.null2String(new weaver.general.BaseBean().getPropValue("weaver_security_type","reversible_enc_type"));
//						if("sm4".equalsIgnoreCase(sm4)&&aescode.startsWith("sm4start")&&aescode.endsWith("sm4end")){
//							InputStream is = null;
//							String _htmlname = temppath + java.util.UUID.randomUUID();
//							try{
//								is = new FileInputStream(f);
//								is = AESCoder.encrypt(is, aescode);
//
//								OutputStream ops = new FileOutputStream(_htmlname);
//								int n = 0;
//								byte []b = new byte[2048];
//								while((n=is.read(b)) != -1){
//									ops.write(b,0,n);
//								}
//								ops.flush();
//								ops.close();
//								is.close();
//								//f.delete();
//								FileSecurityUtil.deleteFile(f);
//								htmlname = _htmlname;
//							}catch(Exception e){
//								new weaver.general.BaseBean().writeLog(e);
//							}
//						}
//					}
                    ImageFileManager imageFileManager = new ImageFileManager();
                    imageFileManager.setComefrom("WorkflowToDoc");
                    imageFileManager.setData(buffer);
                    imageFileManager.setImagFileName(requestname+".html");
                    int imagefileid = imageFileManager.saveImageFile();
//					System.out.println("-在线-imagefileid----"+imagefileid);
                    // 保存imagefile
                    //int imagefileid = saveImageFile(requestname, htmlname, size,false);
                    if (imagefileid <= 0) {
                        log.error("保存在线HTML文件失败");
                        return ;
                    }
                    //把fileid存入fileidsmap中最后一起保存文档-附件关联关系
                    fileids.put("online_html",imagefileid+"");
                    //saveDocDetail(requestname, htmlname, size, workflowid,requestid, wfdocpath,userid);

                    if(g!=null){
                        g.releaseConnection();
                    }
                    if(method!=null){
                        method.releaseConnection();
                    }
                }
            }

        } catch (HttpException e) {
            log.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
            new BaseBean().writeLog(e);
        }finally {
            method.releaseConnection();
        }

    }

    /**
     * 获得最后的url，因为response之后的值，post方法不能直接获取
     * @param client
     * @param url
     * @return
     */
    public String getFinallyUrl(HttpClient client, String url,String cookie) {
        PostMethod g = new PostMethod(url);
        try {
            if(!"".equals(cookie) && cookie != null){
                g.setRequestHeader("cookie", cookie);
            }
            client.executeMethod(g);
        } catch (Exception e) {
            e.printStackTrace();
            return url;
        }
        Header locationHeader = g.getResponseHeader("location");
        if (locationHeader != null) {
            url = locationHeader.getValue();
            url = getFinallyUrl(client, url);
        }
        if (g != null) {
            g.releaseConnection();
        }
        return url;
    }

    public String getFinallyUrl(HttpClient client, String url) {
        return getFinallyUrl(client,url,null);
    }

    //重载下 以防有其他地方调用
    public boolean saveDocDetail(String imagefilename, String workflowid,String requestid, String allwfdocpath,String userid,LinkedHashMap<String,String> fileids,RequestManager requestManager) {
        WfToDocBiz wfbiz = new WfToDocBiz();
        wfbiz.getWfDocPath( workflowid, requestid);
        return this.saveDocDetail(imagefilename,workflowid,requestid,allwfdocpath,userid,fileids,requestManager,wfbiz);
    }
    /**
     * 保存文档信息
     *
     * @param imagefilename
     *            文档名称
     * @param workflowid
     *            流程类型id
     * @param allwfdocpath
     *            文档目录
     * @return 保存是否成功
     */
    public boolean saveDocDetail(String imagefilename, String workflowid,String requestid, String allwfdocpath,String userid,LinkedHashMap<String,String> fileids,RequestManager requestManager,WfToDocBiz wfbiz) {
        RecordSet rs = new RecordSet();
        String wfdocpath[] = Util.TokenizerString2(allwfdocpath, ",");
        int maincategory = 0;
        int subcategory = 0;
        int seccategory = 0;

        if(wfdocpath.length==1){//如果目录就传了一层,默认只给到seccategory
            seccategory = Util.getIntValue(wfdocpath[0],0);
        }else{
            if(wfdocpath.length > 0 ) maincategory = Util.getIntValue(wfdocpath[0],0);
            if(wfdocpath.length > 1 ) subcategory = Util.getIntValue(wfdocpath[1],0);
            if(wfdocpath.length > 2 ) seccategory = Util.getIntValue(wfdocpath[2],0);
        }

        // 保存docdetail
        ResourceComInfo ResourceComInfo = null;
        try {
            ResourceComInfo = new ResourceComInfo();
        } catch (Exception e) {
            log.error(e);
        }
        String sql = "";
        int doclangurage = 7;
        int docowner = Util.getIntValue(getWfDocOwner(workflowid,requestid), 0);
        int docdepartmentid = Util.getIntValue(ResourceComInfo
                .getDepartmentID("" + docowner), 0);
        String docsubject = imagefilename;

        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":"
                + Util.add0(today.get(Calendar.MINUTE), 2) + ":"
                + Util.add0(today.get(Calendar.SECOND), 2);
        String doccreatedate = formatdate;
        String doccreatetime = formattime;
        String doclastmoddate = formatdate;
        String doclastmodtime = formattime;
        String docValidDate = formatdate;
        String docValidTime = formattime;
        String parentids =  "";
        String docCreaterType = "1";
        String docextendname = "html";
        String docCode = "";
        String doccontent = "";
        String clientIp = "";

        rs.executeSql("select clientAddress from SysMaintenanceLog, SystemLogItem where operateitem='60' AND SysMaintenanceLog.operateItem = SystemLogItem.itemId and operateuserid = '" + userid + "' order by id desc");
        rs.next();
        clientIp = rs.getString("clientAddress");

        if("0:0:0:0:0:0:0:1".equals(clientIp)){
            clientIp = "127.0.0.1";
        }

        rs.executeProc("Doc_SecCategory_SelectByID",seccategory+"");
        rs.next();

        String docapprovable = "";
        String docreplyable = rs.getString("replyable");
        String isreply = "";
        int replydocid = 0;
        String docpublishtype = "";

        int itemid = 0;
        int itemmaincategoryid = 0;
        int hrmresid = 0;
        int crmid = 0;
        int projectid = 0;
        int financeid = 0;

        int doccreaterid = docowner;
        int doclastmoduserid = docowner;
        int docapproveuserid = 0;
        String docapprovedate = "";
        String docapprovetime = "";

        int docarchiveuserid = 0;
        String docarchivedate = "";
        String docarchivetime = "";

        String docstatus = "1";
        int assetid = 0;
        int ownerid = docowner;

        String keyword = "";
        int accessorycount = 0;
        String docfiles = getDocFiles(workflowid);
        if (docfiles.contains("1")) {
            accessorycount++;
        }
        if (docfiles.contains("2")) {
            accessorycount++;
        }
        if (docfiles.contains("3")){
            accessorycount++;
        }

        int replaydoccount = 0;
        int docType = 1;//html
        String canCopy = "1";
        String canRemind = "1";
        String orderable = rs.getString("orderable");

        int docEdition = -1;
        int docEditionId = -1;
        SecCategoryComInfo scc =null;

        try {
            scc = new SecCategoryComInfo();
            if(scc.isEditionOpen(seccategory)) {//如果版本管理开启

                docEdition=1;
                docEditionId=this.getNextEditionId();

            }
        } catch (Exception e) {
            log.error(e);
        }
        int isHistory = 0;
        int approveType = 0;
        int mainDoc = 0;
        int readOpterCanPrint = rs.getInt("readoptercanprint");


        int docValidUserId = docowner;
        String invalidationDate = "";
        String docLastModUserType = docCreaterType;
        String docApproveUserType = "";
        String docValidUserType = docCreaterType;
        String docInvalUserType = "";
        String docArchiveUserType = "";
        String docCancelUserType = "";
        String docPubUserType = "";
        String docReopenUserType = "";
        String ownerType = docCreaterType;
        int canPrintedNum = 0;

        int docid = 0;
        List<String> docids = new ArrayList<String> ();
        WorkflowToDocSettingInfoEntity workflowToDocSettingInfoEntity = this.getSettingInfo(workflowid);
        if (isAnnex(workflowToDocSettingInfoEntity)&&fileids.size()>1){  //勾选了关联到表单且为附件字段并且选择的附件种类大于1 则每个附件生成一个文档
            for(Map.Entry<String, String> entry: fileids.entrySet()) {
                try {
                    docid = new DocManager().getNextDocId(rs);
                } catch (Exception e) {
                    log.error("读取文档id号异常：" + e);
                }
                parentids = docid+"";
                mainDoc = docid;
                if ("offline_pdf".equals(entry.getKey())){
                    docsubject = imagefilename+"(PDF)";
                    accessorycount = 1;
                }else if ("offline_html".equals(entry.getKey())){
                    docsubject = imagefilename+"(OfflineHTML)";
                    accessorycount = 1;
                }else if ("online_html".equals(entry.getKey())){
                    docsubject = imagefilename+"(OnlineHTML)";
                    accessorycount = 1;
                }
                SaveDocDetailBiz saveDocDetailBiz = new SaveDocDetailBiz();
                saveDocDetailBiz.setDocid( docid);
                saveDocDetailBiz.setMaincategory( maincategory);
                saveDocDetailBiz.setSubcategory( subcategory);
                saveDocDetailBiz.setSeccategory( seccategory);
                saveDocDetailBiz.setDoclangurage( doclangurage);
                saveDocDetailBiz.setDocapprovable( docapprovable);
                saveDocDetailBiz.setDocreplyable( docreplyable);
                saveDocDetailBiz.setIsreply( isreply);
                saveDocDetailBiz.setReplydocid( replydocid);
                saveDocDetailBiz.setDocsubject( docsubject);
                saveDocDetailBiz.setDocpublishtype( docpublishtype);
                saveDocDetailBiz.setItemid( itemid);
                saveDocDetailBiz.setItemmaincategoryid( itemmaincategoryid);
                saveDocDetailBiz.setHrmresid( hrmresid);
                saveDocDetailBiz.setCrmid( crmid);
                saveDocDetailBiz.setProjectid( projectid);
                saveDocDetailBiz.setFinanceid( financeid);
                saveDocDetailBiz.setDoccreaterid( doccreaterid);
                saveDocDetailBiz.setDocdepartmentid( docdepartmentid);
                saveDocDetailBiz.setDoccreatedate( doccreatedate);
                saveDocDetailBiz.setDoccreatetime( doccreatetime);
                saveDocDetailBiz.setDoclastmoduserid( doclastmoduserid);
                saveDocDetailBiz.setDoclastmoddate( doclastmoddate);
                saveDocDetailBiz.setDoclastmodtime( doclastmodtime);
                saveDocDetailBiz.setDocapproveuserid( docapproveuserid);
                saveDocDetailBiz.setDocapprovedate( docapprovedate);
                saveDocDetailBiz.setDocapprovetime( docapprovetime);
                saveDocDetailBiz.setDocarchiveuserid( docarchiveuserid);
                saveDocDetailBiz.setDocarchivedate( docarchivedate);
                saveDocDetailBiz.setDocarchivetime( docarchivetime);
                saveDocDetailBiz.setDocstatus( docstatus);
                saveDocDetailBiz.setParentids( parentids);
                saveDocDetailBiz.setAssetid( assetid);
                saveDocDetailBiz.setOwnerid( ownerid);
                saveDocDetailBiz.setKeyword( keyword);
                saveDocDetailBiz.setAccessorycount( accessorycount);
                saveDocDetailBiz.setReplaydoccount( replaydoccount);
                saveDocDetailBiz.setUsertype( docCreaterType);
                saveDocDetailBiz.setDoctype(docType);
                saveDocDetailBiz.setCancopy( canCopy);
                saveDocDetailBiz.setCanremind( canRemind);
                saveDocDetailBiz.setOrderable( orderable);
                saveDocDetailBiz.setDocextendname( docextendname);
                saveDocDetailBiz.setDoccode( docCode);
                saveDocDetailBiz.setDocedition( docEdition);
                saveDocDetailBiz.setDoceditionid( docEditionId);
                saveDocDetailBiz.setIshistory( isHistory);
                saveDocDetailBiz.setApproveType( approveType);
                saveDocDetailBiz.setMaindoc( mainDoc);
                saveDocDetailBiz.setReadoptercanprint( readOpterCanPrint);
                saveDocDetailBiz.setDocvaliduserid( docValidUserId);
                saveDocDetailBiz.setDocvaliddate( docValidDate);
                saveDocDetailBiz.setDocvalidtime( docValidTime);
                saveDocDetailBiz.setInvalidationdate( invalidationDate);
                saveDocDetailBiz.setDocCreaterType( docCreaterType);
                saveDocDetailBiz.setDocLastModUserType( docLastModUserType);
                saveDocDetailBiz.setDocApproveUserType( docApproveUserType);
                saveDocDetailBiz.setDocValidUserType( docValidUserType);
                saveDocDetailBiz.setDocInvalUserType( docInvalUserType);
                saveDocDetailBiz.setDocArchiveUserType( docArchiveUserType);
                saveDocDetailBiz.setDocCancelUserType( docCancelUserType);
                saveDocDetailBiz.setDocPubUserType( docPubUserType);
                saveDocDetailBiz.setDocReopenUserType( docReopenUserType);
                saveDocDetailBiz.setOwnerType( ownerType);
                saveDocDetailBiz.setCanPrintedNum( canPrintedNum);
                saveDocDetailBiz.setFromworkflow( requestid);
                saveDocDetailBiz.setDoccontent( doccontent);
                saveDocDetailBiz.setDocowner( docowner);
                saveDocDetailBiz.setClientIp( clientIp);
                saveDocDetailBiz.saveDoc(requestid,requestManager,wfbiz,userid);

                // 最后保存 docimagefile
                if ("offline_pdf".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,3);
                }else if ("offline_html".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,2);
                }else if ("online_html".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,1);
                }
                DocSaveService.copyDocFile(seccategory,docid);

                //解决流程存文档不推动文档消息
                SendMsgForNewDocThread sendThread = new SendMsgForNewDocThread(new User(Util.getIntValue(userid)),docid,null);sendThread.start();
                docids.add(docid+"");
            }
        }else{    //只生成一篇文档
            try {
                docid = new DocManager().getNextDocId(rs);
            } catch (Exception e) {
                log.error("读取文档id号异常：" + e);
                return false;
            }
            parentids = docid+"";
            mainDoc = docid;
            SaveDocDetailBiz saveDocDetailBiz = new SaveDocDetailBiz();
            saveDocDetailBiz.setDocid( docid);
            saveDocDetailBiz.setMaincategory( maincategory);
            saveDocDetailBiz.setSubcategory( subcategory);
            saveDocDetailBiz.setSeccategory( seccategory);
            saveDocDetailBiz.setDoclangurage( doclangurage);
            saveDocDetailBiz.setDocapprovable( docapprovable);
            saveDocDetailBiz.setDocreplyable( docreplyable);
            saveDocDetailBiz.setIsreply( isreply);
            saveDocDetailBiz.setReplydocid( replydocid);
            saveDocDetailBiz.setDocsubject( docsubject);
            saveDocDetailBiz.setDocpublishtype( docpublishtype);
            saveDocDetailBiz.setItemid( itemid);
            saveDocDetailBiz.setItemmaincategoryid( itemmaincategoryid);
            saveDocDetailBiz.setHrmresid( hrmresid);
            saveDocDetailBiz.setCrmid( crmid);
            saveDocDetailBiz.setProjectid( projectid);
            saveDocDetailBiz.setFinanceid( financeid);
            saveDocDetailBiz.setDoccreaterid( doccreaterid);
            saveDocDetailBiz.setDocdepartmentid( docdepartmentid);
            saveDocDetailBiz.setDoccreatedate( doccreatedate);
            saveDocDetailBiz.setDoccreatetime( doccreatetime);
            saveDocDetailBiz.setDoclastmoduserid( doclastmoduserid);
            saveDocDetailBiz.setDoclastmoddate( doclastmoddate);
            saveDocDetailBiz.setDoclastmodtime( doclastmodtime);
            saveDocDetailBiz.setDocapproveuserid( docapproveuserid);
            saveDocDetailBiz.setDocapprovedate( docapprovedate);
            saveDocDetailBiz.setDocapprovetime( docapprovetime);
            saveDocDetailBiz.setDocarchiveuserid( docarchiveuserid);
            saveDocDetailBiz.setDocarchivedate( docarchivedate);
            saveDocDetailBiz.setDocarchivetime( docarchivetime);
            saveDocDetailBiz.setDocstatus( docstatus);
            saveDocDetailBiz.setParentids( parentids);
            saveDocDetailBiz.setAssetid( assetid);
            saveDocDetailBiz.setOwnerid( ownerid);
            saveDocDetailBiz.setKeyword( keyword);
            saveDocDetailBiz.setAccessorycount( accessorycount);
            saveDocDetailBiz.setReplaydoccount( replaydoccount);
            saveDocDetailBiz.setUsertype( docCreaterType);
            saveDocDetailBiz.setDoctype(docType);
            saveDocDetailBiz.setCancopy( canCopy);
            saveDocDetailBiz.setCanremind( canRemind);
            saveDocDetailBiz.setOrderable( orderable);
            saveDocDetailBiz.setDocextendname( docextendname);
            saveDocDetailBiz.setDoccode( docCode);
            saveDocDetailBiz.setDocedition( docEdition);
            saveDocDetailBiz.setDoceditionid( docEditionId);
            saveDocDetailBiz.setIshistory( isHistory);
            saveDocDetailBiz.setApproveType( approveType);
            saveDocDetailBiz.setMaindoc( mainDoc);
            saveDocDetailBiz.setReadoptercanprint( readOpterCanPrint);
            saveDocDetailBiz.setDocvaliduserid( docValidUserId);
            saveDocDetailBiz.setDocvaliddate( docValidDate);
            saveDocDetailBiz.setDocvalidtime( docValidTime);
            saveDocDetailBiz.setInvalidationdate( invalidationDate);
            saveDocDetailBiz.setDocCreaterType( docCreaterType);
            saveDocDetailBiz.setDocLastModUserType( docLastModUserType);
            saveDocDetailBiz.setDocApproveUserType( docApproveUserType);
            saveDocDetailBiz.setDocValidUserType( docValidUserType);
            saveDocDetailBiz.setDocInvalUserType( docInvalUserType);
            saveDocDetailBiz.setDocArchiveUserType( docArchiveUserType);
            saveDocDetailBiz.setDocCancelUserType( docCancelUserType);
            saveDocDetailBiz.setDocPubUserType( docPubUserType);
            saveDocDetailBiz.setDocReopenUserType( docReopenUserType);
            saveDocDetailBiz.setOwnerType( ownerType);
            saveDocDetailBiz.setCanPrintedNum( canPrintedNum);
            saveDocDetailBiz.setFromworkflow( requestid);
            saveDocDetailBiz.setDoccontent( doccontent);
            saveDocDetailBiz.setDocowner( docowner);
            saveDocDetailBiz.setClientIp( clientIp);
            saveDocDetailBiz.saveDoc(requestid,requestManager,wfbiz,userid);

            // 最后保存 docimagefile
            for(Map.Entry<String, String> entry: fileids.entrySet()) {
                if ("offline_pdf".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,3);
                }else if ("offline_html".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,2);
                }else if ("online_html".equals(entry.getKey())){
                    saveDocImageFile(docid, Util.getIntValue(entry.getValue()), imagefilename,1);
                }
            }
            DocSaveService.copyDocFile(seccategory,docid);
            //解决流程存文档不推动文档消息
            SendMsgForNewDocThread sendThread = new SendMsgForNewDocThread(new User(Util.getIntValue(userid)),docid,null);sendThread.start();
            docids.add(docid+"");
            this.fileId = docid;
        }

        //文档保存到表单字段
        saveDocToForm(rs,String.join(",",docids),docowner,requestid,workflowid);
        return true;
    }

    /*
     * 文档关联到表单字段   支持多个文档更新到表单字段
     */
    public boolean saveDocToForm(RecordSet rs,String docids,int docowner,String requestid,String workflowid){
        String sql = "";
        String[] docidarr = docids.split(",");

        String tablename = " workflow_form ";
        String fieldname = "";
        String fieldhtmltype ="";
        String type ="";
        rs.executeQuery("select formid,isbill,wfdocrelatedformdisplay,wfdocrelatefieldid from workflow_base where id = ?",workflowid);
        RecordSet rs1 = new RecordSet();
        if (rs.next()){
            String wfdocrelatedformdisplay = Util.null2String(rs.getString("wfdocrelatedformdisplay"));
            String wfdocrelatefieldid = Util.null2String(rs.getString("wfdocrelatefieldid"));
            int isbill = Util.getIntValue(rs.getString("isbill"), 0);
            int formid = Util.getIntValue(rs.getString("formid"), 0);
            if(wfdocrelatedformdisplay.equals("1")&&!wfdocrelatefieldid.equals("")){
                if(isbill == 1){
                    sql = "select tablename from workflow_bill where id="+formid;
                    rs1.executeQuery(sql);
                    if(rs1.next()){
                        tablename = Util.null2String(rs1.getString(1));
                    }
                    sql = "select fieldname,fieldhtmltype,type from workflow_billfield where billid="+formid+" and id="+wfdocrelatefieldid;
                }else{
                    sql = "select fieldname,fieldhtmltype,type from workflow_formdictdetail where id="+wfdocrelatefieldid;
                }
                rs1.executeQuery(sql);
                if(rs1.next()){
                    fieldname = Util.null2String(rs1.getString(1));
                    fieldhtmltype =Util.null2String(rs1.getString(2));
                    type =Util.null2String(rs1.getString(3));
                }
                if(!"".equals(tablename) && !"".equals(fieldname)){
                    String fieldvalue ="";  //先获取数据库原有值
                    sql = "select "+fieldname+" from "+tablename+" where requestid="+requestid;
                    rs1.executeQuery(sql);
                    if(rs1.next()){
                        fieldvalue = Util.null2String(rs1.getString(1));
                    }
                    if (!fieldvalue.equals("")){
                        if ((fieldhtmltype.equals("6")&&type.equals("1"))||(fieldhtmltype.equals("3")&&type.equals("37"))){    //附件和多文档字段 追加
                            String updateDocids = fieldvalue+","+docids;
                            rs1.executeUpdate(" update "+tablename+" set "+fieldname+" = '"+updateDocids+"' where  requestid = ?",requestid);
                        }else if (fieldhtmltype.equals("3")&&type.equals("9")){  //单文档  会清除原文档再添加
                            rs1.executeUpdate(" update "+tablename+" set "+fieldname+" = '"+docids+"' where  requestid = ?",requestid);
                            new BaseBean().writeLog("流程存文档关联到表单字段，单文档字段原先值==>"+fieldvalue+",更新后docid ==>"+docids);
                        }
                    }else {
                        rs1.executeUpdate(" update "+tablename+" set "+fieldname+" = '"+docids+"' where  requestid = ?",requestid);
                    }
                }
            }

            /*  更新完成后给流程所有操作者赋权*****/
            WfToDocBiz.docShare(docids,requestid,docowner);

        }
        return true;
    }


    /**
     * 判断requestmanager是否为空
     * @param rmanager
     */
    public RequestManager getRequestManager(RequestManager rmanager,String requestid){
        if(rmanager==null){
            rmanager = new RequestManager();
            RecordSet rs = new RecordSet();
            String sql = "select * from workflow_requestbase where requestid = " + requestid;
            rs.executeSql(sql);
            while(rs.next()){
                int _requestId=rs.getInt("requestid");
                int workflowId=rs.getInt("workflowid");
                int creater=rs.getInt("creater");
                String requestname = rs.getString("requestname");
                String requestlevel = rs.getString("requestlevel");
                String messagetype = rs.getString("messagetype");
                rmanager.setRequestid(_requestId);
                rmanager.setWorkflowid(workflowId);
                rmanager.setCreater(creater);
                rmanager.setRequestname(requestname);
                rmanager.setRequestlevel(requestlevel);
                rmanager.setMessageType(messagetype);
                rmanager.setNodeid(Util.getIntValue(rs.getString("currentNodeID")));
            }
        }

        return rmanager;
    }

    //重载下 以防方法在其他地方有调用
    public boolean saveDocProp(int docid,String requestid,RequestManager requestManager){
        return saveDocProp( docid, requestid, requestManager,new WfToDocBiz());
    }
    /**
     * 保存文档属性
     * @param docid
     * @return
     */
    public boolean saveDocProp(int docid,String requestid,RequestManager requestManager,WfToDocBiz wfbiz){
        boolean success = true;
        String docids = docid+"";
        requestManager = getRequestManager(requestManager,requestid);
        try{
            log.error("saveDocProp:" + docid +" "+requestid);
            RequestDocPropManager requestDocPropManager=new RequestDocPropManager(wfbiz);
            requestDocPropManager.changeDocProp(requestManager,docids);
        }catch (Exception e) {
            success = false;
            log.error("RequestDocPropManager Error:requestid="+requestid+"###docids="+docids);
            log.error(e);
        }
        log.error("success:"+success);
        return success;

    }

    /**
     * 保存docimagefile
     *
     * @param docid
     *            文档id
     * @param imagefileid
     *            imagefileid
     * @param filename
     *            文件名
     */
    public boolean saveDocImageFile(int docid, int imagefileid, String filename,int filetype) {
        RecordSet rs = new RecordSet();
        int id = 0;
        int versionId = 0;
        String imagefiledesc = "";
        String imagefilewidth = "0";
        String imagefileheight = "0";
        String imagefielsize = "0";
        String docfiletype = "2";
        String versionDetail = "";
        try {
            id = new DocImageManager().getNextDocImageFileId();
        } catch (Exception e) {
            log.error("读取docimagefileid异常：" + e);
            return false;
        }
        versionId=versionIdUpdate.getVersionNewId();
        String tmpsqlstr = "INSERT INTO DocImageFile(docid, imagefileid, imagefilename, imagefiledesc, imagefilewidth, imagefileheight, imagefielsize, docfiletype,versionId,versionDetail,id)"
                + "VALUES ("
                + ""
                + docid
                + ""
                + ","
                + ""
                + imagefileid
                + ""
                + ","
                + "'"
                + filename
                + "'"
                + ","
                + "'"
                + imagefiledesc
                + "'"
                + ","
                + "'"
                + imagefilewidth
                + "'"
                + ","
                + "'"
                + imagefileheight
                + "'"
                + ","
                + ""
                + imagefielsize
                + ""
                + ","
                + "'"
                + docfiletype
                + "'"
                + ","
                + ""
                + versionId
                + ""
                + ","
                + "'" + versionDetail + "'" + "," + id + ")";
        rs.executeSql(tmpsqlstr);
        return true;
    }

    /**
     * 保存imagefile 返回文件的id
     *
     * @param filename
     *            文件名
     * @param filerealpath
     *            文件绝对路径
     * @param filesize
     *            文件大小
     * @return imagefileid 文件id
     */
    public int saveImageFile(String filename, String filerealpath, long filesize,boolean ispdf) {
        int imageid = 0;
        String contenttype = "";
        String imagefileused = "1";
        String iszip = "0";
        String isencrypt = "0";
        RecordSet rs = new RecordSet();
        char separator = Util.getSeparator();
        imageid=imageFileIdUpdate.getImageFileNewId();
        String para = "" + imageid + separator + filename + separator
                + contenttype + separator + imagefileused + separator
                + filerealpath + separator + iszip + separator + isencrypt
                + separator + filesize;
        rs.executeProc("ImageFile_Insert", para);
        return imageid;
    }

    /**
     * 获取系统的路径
     *
     * @return
     */
    public String getSystemPath() {
        String path = GCONST.getPropertyPath();
        path = path.substring(0, path.indexOf("WEB-INF"));
        path = Util.StringReplace(path, "\\", "/");
        return path;
    }

    //判断是否开启了文档关联到表单并选择了附件字段
    public boolean isAnnex(WorkflowToDocSettingInfoEntity workflowToDocSettingInfoEntity) {
        RecordSet rs =  new RecordSet();
        if (workflowToDocSettingInfoEntity.getWfdocrelatedformdisplay().equals("1")){
            String sql = "";
            if(workflowToDocSettingInfoEntity.getIsbill()==0)
                sql = "select fieldhtmltype from workflow_formdict where id = ? ";
            else
                sql = "select fieldhtmltype as name from workflow_billfield where  id =? ";
            rs.executeQuery(sql,workflowToDocSettingInfoEntity.getWfdocrelatefieldid());
            if (rs.next()&&Util.null2String(rs.getString(1)).equals("6")){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取设置信息
     * @return
     */
    private WorkflowToDocSettingInfoEntity getSettingInfo(String workflowId){
        int isbill = 1;
        String wfdocpath = "";
        String wfdocownertype = "";
        String wfdocownerfieldid = "";
        String wfdocowner="";
        int keepsign = 0;
        String docfiles = "";
        String wfdocpathtype = "";   //文档存储路径类型 固定目录1  选择目录2
        String wfdocpathfieldid = "";  //文档存储路径字段
        String wfdocsource = "";  //附件来源
        String wfdocrelatedformdisplay = "";  //文档关联到表单显示
        String wfdocrelatefieldid = "";  //关联字段
        String wfdocdiaplaywatermark = ""; //展示流程水印
        RecordSet rs = new RecordSet();
        rs.executeQuery("select isbill,wfdocowner,wfdocownertype,wfdocownerfieldid,keepsign,wfdocpath,docfiles,wfdocpathtype,wfdocpathfieldid,wfdocsource,wfdocrelatedformdisplay,wfdocrelatefieldid,wfdocdiaplaywatermark from workflow_base where id = ?" , workflowId);
        if(rs.next()) {
            wfdocowner = rs.getString("wfdocowner");
            wfdocownertype = rs.getString("wfdocownertype");
            wfdocownerfieldid = rs.getString("wfdocownerfieldid");
            keepsign = rs.getInt("keepsign");
            wfdocpath = rs.getString("wfdocpath");
            docfiles = rs.getString("docfiles");
            wfdocpathtype = rs.getString("wfdocpathtype");
            wfdocpathfieldid = rs.getString("wfdocpathfieldid");
            wfdocsource = rs.getString("wfdocsource");
            wfdocrelatedformdisplay = rs.getString("wfdocrelatedformdisplay");
            wfdocrelatefieldid = rs.getString("wfdocrelatefieldid");
            wfdocdiaplaywatermark = rs.getString("wfdocdiaplaywatermark");
            isbill = Util.getIntValue(rs.getString("isbill"));
        }

        return new WorkflowToDocSettingInfoEntity(wfdocpath,wfdocownertype,wfdocownerfieldid,wfdocowner,keepsign,docfiles,wfdocpathtype,wfdocpathfieldid,wfdocsource,wfdocrelatedformdisplay,wfdocrelatefieldid,wfdocdiaplaywatermark,isbill);
    }
    /*
     *得到keepsign 是否保留签字意见
     */
    public int getKeepSign(String workflowid){
        RecordSet rs = new RecordSet();
        int keepsign = 0;
        rs.executeQuery("select keepsign from workflow_base where id = ?",workflowid);
        if (rs.next()){
            keepsign = rs.getInt("keepsign");
        }
        return keepsign;
    }
    /*
     * 得到docfiles  文档附件 在线表单/离线表单(HTML)/离线表单(PDF)
     */
    public String getDocFiles(String workflowid){
        RecordSet rs = new RecordSet();
        String docfiles = "";
        String wfdocpath = "";
        rs.executeQuery("select docfiles,wfdocpath from workflow_base where id = ?",workflowid);
        if (rs.next()){
            docfiles = Util.null2String(rs.getString("docfiles"));
            wfdocpath = Util.null2String(rs.getString("wfdocpath"));
        }
        if ("".equals(docfiles)&&!"".equals(wfdocpath)){
            docfiles="1";
            rs.executeUpdate("update workflow_base set docfiles ='1' where id = ?",workflowid);
        }
        return docfiles;
    }
    /**
     * 获得文档存放的目录
     *
     * @param workflowid
     * @return 主目录,分目录,子目录
     */
    public String getWfDocPath(String workflowid) {
        String wfdocpath = "";
        RecordSet rs = new RecordSet();
        String sql = "select * from workflow_base where id = '" + workflowid
                + "'";
        rs.executeSql(sql);
        rs.next();
        wfdocpath = Util.null2String(rs.getString("wfdocpath"));
        return wfdocpath;
    }

    /**
     * 获得文档的所有者
     *
     * @param workflowid
     * @return resourceid
     */
    public String getWfDocOwner(String workflowid,String requestid) {
        int wfdocowner = 0;
        try{
            String sql = "";
            int wfid = Util.getIntValue(workflowid, 0);
            int rid = Util.getIntValue(requestid, 0);
            if(wfid<=0 || rid<=0){
                return "0";
            }
            RecordSet rs = new RecordSet();
            sql = "select * from workflow_base where id="+wfid;
            rs.executeSql(sql);
            if(rs.next()){
                int wfdocowner_tmp = Util.getIntValue(rs.getString("wfdocowner"), 0);
                int wfdocownertype_tmp = Util.getIntValue(rs.getString("wfdocownertype"), 0);
                int wfdocownerfieldid_tmp = Util.getIntValue(rs.getString("wfdocownerfieldid"), 0);
                int isbill = Util.getIntValue(rs.getString("isbill"), 0);
                int formid = Util.getIntValue(rs.getString("formid"), 0);
                if(wfdocownertype_tmp == 1){
                    wfdocowner = wfdocowner_tmp;
                }else if(wfdocownertype_tmp == 2){
                    String tablename = " workflow_form ";
                    String fieldname = "";
                    if(isbill == 1){
                        sql = "select tablename from workflow_bill where id="+formid;
                        rs.execute(sql);
                        if(rs.next()){
                            tablename = Util.null2String(rs.getString(1));
                        }
                        sql = "select fieldname from workflow_billfield where billid="+formid+" and id="+wfdocownerfieldid_tmp;
                    }else{
                        sql = "select fieldname from workflow_formdict where id="+wfdocownerfieldid_tmp;
                    }
                    rs.execute(sql);
                    if(rs.next()){
                        fieldname = Util.null2String(rs.getString(1));
                        if(!"".equals(tablename) && !"".equals(fieldname)){
                            sql = "select "+fieldname+" from "+tablename+" where requestid="+rid;
                            rs.execute(sql);
                            if(rs.next()){
                                String fieldvalue = Util.null2String(rs.getString(1));
                                if(!"".equals(fieldvalue)){
                                    int index = fieldvalue.indexOf(",");
                                    if(index > -1){
                                        fieldvalue = fieldvalue.substring(0, index);
                                    }
                                    wfdocowner = Util.getIntValue(fieldvalue);
                                }
                            }
                        }
                    }
                }
                String status = Util.null2String(new ResourceComInfo().getStatus(""+wfdocowner));
                if(status.equals("0") || status.equals("1") || status.equals("2") || status.equals("3")){
                    //do nothing
                }else{
                    wfdocowner = 0;
                }
            }
        }catch(Exception e){

        }
        if(wfdocowner <= 0){
            wfdocowner = 1;
        }
        return ""+wfdocowner;
    }

    /**
     * 获得文件保存目录
     *
     * @return
     */
    public String getFileSavePath() {
        SystemComInfo syscominfo = new SystemComInfo();
        String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());
        return createdir;
    }

    public synchronized int getNextEditionId() throws Exception {
        int docindex = 0;
        RecordSet rs = new RecordSet();
        rs.executeProc("SequenceIndex_SelectNextID", "doceditionid");
        if (rs.next())
            docindex = rs.getInt(1);
        return docindex;
    }

}
